import efinance as ef
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import re

plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号

data_kua = pd.read_excel(r'c:\Users\Lenovo\Desktop\跨境etf代码表.xlsx')
code_names = data_kua['thscode']
code_data = []
shouyilvlist = []
print(code_names)
for i in code_names:
    if i not in code_data:
        code_data.append(i)
print(code_data)

db_all_ = []

neam_ids = ef.futures.get_futures_base_info()
hua = 0.01
def get_name_index(name):
    return neam_ids['行情ID'][neam_ids[neam_ids['期货名称'] == f'{name}'].index.tolist()[0]]

def split_to_data(data,name,wheel):
    data_wheel = []
    for i in range(5,len(data)):
        data_wheel.append(np.average(data[name][i-wheel:i-1]))
    return data_wheel
def find_h_l(data,wheel):
    data_h = []
    data_l = []
    close_h = []
    close_l = []
    for i in range(5, len(data)):
        data_h.append(np.max(data['最高'][i - wheel:i - 1]))
        data_l.append(np.min(data['最低'][i - wheel:i - 1]))
        close_h.append(np.max(data['收盘'][i - wheel:i - 1]))
        close_l.append(np.min(data['收盘'][i - wheel:i - 1]))
    return data_h,data_l,close_h,close_l

def one_to(data_to_one):
    one_to_data = []
    pif = np.max(data_to_one) - np.min(data_to_one)
    for i in data_to_one:
        one_to_data.append((i - np.min(data_to_one))/pif)
    return one_to_data

def get_have(name:str)->str:
    name = re.findall("\d+",name)[0]
    return name

def wlh(address,grid):
    if address[0] != grid:
        return True
    else:
        return False

def get_shouyilv(data_do:pd.DataFrame):
    data = np.array(data_do[1])
    index_list = data_do[0][data_do[0]=='卖出'].index.tolist()
    index_list.insert(0,0)
    sum_ = 0
    for i in range(len(index_list)-1):
        end = data[index_list[i+1]]
        k = 1
        if i == 0:
            k = 0
        for j in range(index_list[i]+k,index_list[i+1]):
            sum_ += (data[j]-end)/data[j]
    # print(sum_)
    return sum_
def main(index):
    """
    k1 = 0.5
    k2 = 0.1
    """
    cc = []
    k1 = 1
    k2 = 1
    wheel = 5
    id_futures = str(513130)
    guo = 0.02
    ####网格交易参数
    data_do = [[-3]]
    address = [0,0]
    get_buy_data = 0
    last_ = 0
    max_volume = 15
    data_base = ef.stock.get_quote_history(id_futures, klt=5)
    if len(data_base) == 0:
        return
    # data_day = np.array(data_base['日期'])
    data_base_open = np.array(data_base['开盘'])
    data_base_close = np.array(data_base['收盘'])
    # data_base_zdf = np.array(data_base['涨跌幅'])
    benefit = []
    for i in range(len(data_base_close)-1):
        benefit.append(data_base_close[i+1]/data_base_close[i])
    beta = np.cov(benefit)/np.var(benefit)
    # yuzhi = (data_base_zdf.max()-data_base_zdf.min())/2
    # print(data_base_zdf)
    # print(data_base.columns)
    # print(data_base)
    data_h, data_l, close_h, close_l = find_h_l(data_base,wheel)
    public_dates = ef.fund.get_public_dates(id_futures)
    kk = ef.fund.get_invest_position(id_futures, dates=public_dates[0])
    try:
        bodonglv = ((np.sum(kk['持仓占比']*kk['较上期变化'],axis=0))/10)
    except:
        bodonglv = None
    # grid = pd.cut([bar.close], context.band, labels=[1, 2, 3, 4, 5, 6, 7, 8])[0]
    for i in range(5,len(data_h)+5):
        before = i-1
        center = data_base_close[before]
        wg = np.array([0.92, 0.94, 0.96, 0.98, 1, 1.02, 1.04, 1.06, 1.08]) * center
        grid = pd.cut([data_base_close[i]], wg, labels=[1, 2, 3, 4, 5, 6, 7, 8])[0]
        range_k = max(data_h[i-5]-close_l[i-5],close_h[i-5]-data_l[i-5])
        buy_line = data_base_open[i] + k1*range_k
        sell_line = data_base_open[i] - k2*range_k
        if get_buy_data >= 8:
            data_do.append(['卖出', data_base_close[i], i])
            get_buy_data = 0
        if last_ < grid and wlh(address,grid):
            data_do.append(['买涨', data_base_close[i], i])
            get_buy_data += 1
        address = [last_, grid]
        last_ = grid
        if data_base_close[i] > buy_line:
            # if data_do[-1][0] != '买涨':
            data_do.append(['买涨',data_base_close[i],i])
            get_buy_data += 1
        if data_base_close[i] < sell_line:
            if data_do[-1][0] == '买涨':
                # print('卖出',data_base_close[i])
                data_do.append(['卖出', data_base_close[i],i])
                get_buy_data = 0

        # try:
        #     if data_do[-1][0] == '买涨' and data_base_zdf[i] > 0:
        #         # if data_base_zdf[i] > 0.6:
        #         #     data_do.append(['卖出', data_base_close[i], i])
        #         pass
        #     elif data_do[-1][0] == '买涨' and data_base_zdf[i] < 0:
        #         if data_base_zdf[i] < -yuzhi:
        #             data_do.append(['卖出', data_base_close[i], i])
        #     elif data_do[-1][0] != '买涨' and data_base_zdf[i] < 0:
        #         # if data_base_zdf[i] < -0.6:
        #         #     data_do.append(['买涨', data_base_close[i], i])
        #         pass
        #     elif data_do[-1][0] != '买涨' and data_base_zdf[i] > 0:
        #         if data_base_zdf[i] > yuzhi:
        #             data_do.append(['买涨', data_base_close[i], i])
        # except:
        #     pass
        if i == len(data_h)+4:
            data_do.append(['卖出', data_base_close[i], i])
            get_buy_data = 0
    data_do = data_do[1:]
    plt.plot(range(len(data_base_close)),data_base_close)
    a = []
    b = []
    for d_dat in data_do:
        color = str
        if d_dat[0] != '买涨':
            color = 'g'
            a = plt.scatter(d_dat[2], d_dat[1], c=color)
        else:
            color = 'r'
            b = plt.scatter(d_dat[2],d_dat[1],c = color)

    plt.legend((a, b), ('卖出', '买入'), loc='best')
    plt.show()
    data_do = pd.DataFrame(data_do)
    print(data_do)
    # data_do.to_excel(rf'C:\Users\Lenovo\Desktop\A金融大湾区\回测数据\第二题\{id_futures}.xlsx')
    # print(data_do)
    shouyilv = get_shouyilv(data_do)
    try:
        xpl = (shouyilv - guo)/bodonglv
    except:
        xpl = None
    print(f'{id_futures}收益率:',shouyilv)

    shouyilvlist.append([id_futures,xpl,beta,shouyilv])


    # data_do_frame = pd.DataFrame(data_do[1:],columns=['方式','收盘价','时间'])
    # plt.subplot(2,1,1)
    # win_number = 0
    # for x,y,tp in zip(data_do_frame['时间'],data_do_frame['收盘价'],data_do_frame['方式']):
    #     if tp == '买涨':
    #         plt.scatter(x,y,c = 'r')
    #     if tp == '卖出':
    #         plt.scatter(x,y,c = 'g')

    # plt.subplot(2, 1, 2)
    # plt.plot(range(len(data_base['涨跌幅'])),one_to(data_base['涨跌幅']))
    # plt.show()
    # win_arr = []
    # lose_arr = []
    # data_do = data_do[1:]
    # print('夏普率:',xpl)
    # print(f'k1:{k1},k2:{k2}')
    # print('--------------------------------------------------')
    # db_all_.append([data_do,xpl,shouyilv,beta])
for index in range(1,19):
    to_get_index = pd.read_excel(fr'C:\Users\Lenovo\Desktop\A金融大湾区\回测数据\第三题\第{index}天得分表.xlsx')
    to_get_index_code = np.array(to_get_index.sort_values('得分')[-5:]['ETF代码'])
    to_get_score = np.array(to_get_index.sort_values('得分')[-5:]['得分'])
    for i,j in zip(to_get_index_code,to_get_score):
        main(i)
    shouyilvlist.append(['----','----','----','----'])
    end_data = pd.DataFrame(shouyilvlist, columns=['代码', '夏普率', 'Beta', '收益率'])
    end_data.to_excel(r'C:\Users\Lenovo\Desktop\A金融大湾区\回测数据\第三题\收益率(网格交易法+Dual_Thrust).xlsx', index_label=None)